package org.com.gamemall.Controller;

import com.aliyun.oss.*;
import com.aliyun.oss.common.auth.CredentialsProviderFactory;
import com.aliyun.oss.common.auth.EnvironmentVariableCredentialsProvider;
import com.aliyun.oss.common.comm.SignVersion;
import com.aliyun.oss.internal.OSSHeaders;
import com.aliyun.oss.model.*;
import lombok.extern.slf4j.Slf4j;
import org.com.gamemall.Entity.Oss;
import org.com.gamemall.Service.IOssService;
import org.com.gamemall.Utity.UserHolder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.UUID;
@Slf4j
@RestController
@RequestMapping("/common")
public class CommonController {
    @Autowired
    private IOssService ossService;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @PostMapping("/upload")
    public String upload(MultipartFile file) throws Exception {
        String endpoint = "https://oss-cn-chengdu.aliyuncs.com";
        // 从环境变量中获取访问凭证。运行本代码示例之前，请确保已设置环境变量OSS_ACCESS_KEY_ID和OSS_ACCESS_KEY_SECRET。
        EnvironmentVariableCredentialsProvider credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider();
        String bucketName = "bucket-soouth1";
        String objectName = "south/southobject";
        String region = "cn-chengdu";

        // 创建OSSClient实例。
        // 当OSSClient实例不再使用时，调用shutdown方法以释放资源。
        ClientBuilderConfiguration clientBuilderConfiguration = new ClientBuilderConfiguration();
        clientBuilderConfiguration.setSignatureVersion(SignVersion.V4);
        OSS ossClient = OSSClientBuilder.create()
                .endpoint(endpoint)
                .credentialsProvider(credentialsProvider)
                .clientConfiguration(clientBuilderConfiguration)
                .region(region)
                .build();

        try {
            // 生成唯一的文件名
            String originalFilename = file.getOriginalFilename();
            String fileExtension = originalFilename.substring(originalFilename.lastIndexOf("."));
            String filename = "uploads/" + UUID.randomUUID() + fileExtension;

            // 创建元数据
            ObjectMetadata metadata = new ObjectMetadata();
            metadata.setContentType(file.getContentType());
            metadata.setContentLength(file.getSize());
            metadata.setHeader("OSSStorageClass", StorageClass.Standard.toString());

            // 创建上传请求
            PutObjectRequest putObjectRequest = new PutObjectRequest(
                    bucketName,
                    objectName,
                    file.getInputStream(),
                    metadata
            );

            // 上传文件
            PutObjectResult result = ossClient.putObject(putObjectRequest);
            log.info("文件上传成功，ETag: {}", result.getETag());

            // 生成访问URL
            String fileUrl = "https://" + bucketName + ".oss-cn-chengdu.aliyuncs.com/" + objectName;
            Oss oss = new Oss();
            oss.setOssFileName(filename);
            oss.setOssUrl(fileUrl);
            String id = stringRedisTemplate.opsForValue().get("login:user:");
            oss.setUserId(Long.valueOf(id));
            ossService.save(oss);
            return "上传成功！文件URL: " + fileUrl;

        } catch (
                IOException e) {
            log.error("文件上传失败", e);
            return "文件上传失败: " + e.getMessage();
        } catch (Exception e) {
            log.error("OSS连接失败", e);
            return "OSS服务异常: " + e.getMessage();
        }
    }
}

